import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools,Flex,Icon,ActivityIndicator,Toast } from 'weaver-mobile';
import {Route, withRouter } from 'react-router-dom';
import { RouteLayout,DocumentTitle } from 'weaver-mobile-page';
import {_scanQRCode,_chooseInvoice,getCpUser} from '../../util/pulic-func';
import AutoCheck from './AutoCheck'
const getLabel = Tools.getLabel;


@withRouter
@inject ('receptionStore','baseStore')
@observer
class Reception extends React.Component {
    constructor(props){
        super(props);
    }

    static defaultProps = {
        prefixCls:"fna-reception"
    }

    componentWillMount(){
        const {baseStore} = this.props;
        const { getTheme,getEquipmentFn } = baseStore;
        getTheme();
        getEquipmentFn();
    }

    componentDidMount() {
        const {receptionStore,baseStore} = this.props;
        const { initData } = receptionStore;
        const { invoiceCloudInfo,getInvoiceCloudToken } = baseStore;

        if(invoiceCloudInfo.invoiceCloud == undefined){
            getInvoiceCloudToken({},()=>{
                invoiceCloudInfo.invoiceCloud === true ? initData({},()=>{ this.loadIframe();}) : initData();
            });
        }else{
            invoiceCloudInfo.invoiceCloud === true ? initData({},()=>{ this.loadIframe();}) : initData();
        }

        window.addEventListener('message',this.receiver,false);
    }

    componentWillUnmount(){
        const {receptionStore} = this.props;
        const { clearData } = receptionStore;
        clearData();
        window.removeEventListener('message',this.receiver,false)
    }  


    render() {
        const { receptionStore,prefixCls,baseStore } = this.props;
        const { receptionList,autoCheckRoute,checkJson,invoiceResult,enabled,loading } = receptionStore;
        const { invoiceCloudInfo,theme,getInvoiceCloudUrl } = baseStore;

        let _enabled = JSON.stringify(enabled);

        return (
            <div className={`${prefixCls}`}>
                <DocumentTitle data={[{ match: /^\/reception/i, title: () => getLabel(516432,'发票录入') }]} defaultTitle="" />
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading}
                />                
                {
                    invoiceCloudInfo.invoiceCloud === false ? 
                    <div className={'multi-col-layouts'}>
                        <Flex className={`fna-flex-icon fna-flex-icon-02`} style={{padding:'20px 10px'}}>
                            {receptionList && receptionList.map( item => {
                                let comment = [
                                    <Flex.Item className={`fna-flex-icon-item`} key={item.key} onClick={()=>{this.routeTo(item.key)}}>
                                        <div className={`fna-flex-icon-item-icon`}><Icon type={item.icon} size={'lg'}/></div>
                                        <div className={`fna-flex-icon-item-text`}>{item.text}</div>
                                    </Flex.Item>
                                ]
                                
                                return comment
                            })}
                        </Flex>
                    </div>
                    :
                    (invoiceCloudInfo.invoiceCloud === true && _enabled != '{}' &&
                        <iframe 
                            className='ec-iframe' 
                            src={getInvoiceCloudUrl('reception',3,{theme:encodeURIComponent(JSON.stringify(theme)),enabled:encodeURIComponent(_enabled),source:'EC_INDEX'})}
                            style={{width:'100%',height:'100%',border:'0'}}
                            id={'myIframe'}
                        >
                        </iframe>
                    )
                }

                <Route
                    key={autoCheckRoute.id}
                    path={autoCheckRoute.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="crmListLayout"
                                    className="wm-route-layout"
                                >
                                    <AutoCheck isForm={false} invoiceResult={invoiceResult} checkJson={checkJson}/>
                                </div>
                            </RouteLayout>
                        )
                    }}
                    /> 
            </div>
        )
    }

    loadIframe = () =>{
        const { setLoading } = this.props.receptionStore;
        let childFrame = document.getElementById("myIframe");
        childFrame.addEventListener("load", function() {
            setLoading(false);
        }, false);
    }

    //路由跳转
    routeTo=(key)=>{
        const { receptionStore,history } = this.props;
        const { autoCheckRoute,getInvoiceInfoByCheck } = receptionStore;
        if(key == 'QRcode'){
            _scanQRCode((value)=>{
                getInvoiceInfoByCheck({result:value},()=>{
                    this.props.history.push(autoCheckRoute.path)
                })
            })
        }else{
            history.push(`ocr?type=${key}`)
        }
        
    
    }

    /* ***********************发票云********************************/
    receiver = (event) =>{
        const {baseStore} = this.props;
        const {equipment,invoiceCloudInfo} = baseStore;
        if (invoiceCloudInfo.jsUrl != event.origin) return;
        let returnData = event.data;
        console.log('reception ----returnData',returnData);

        switch(returnData.type){
            case 'ERROR' :  //token失效
                if(returnData.ret == '-2'){
                    this.sendResult('UPDATE_TOKEN');
                }

                break;
            case 'ON_SCAN_QRCODE' : //调用扫码
                _scanQRCode((value) =>{
                    let params = {
                        source: "ENTRY",
                        type: "SCAN_QRCODE",
                        rid: returnData.rid , // 发票云传过来的 id
                        result: value, // 扫码结果
                    }

                    this.sendResult('SCAN_QRCODE',params);
                    
                });
                break; 
            case 'ON_SELECT_INVOICE': //选择发票   类型：1 微信  2 支付宝
                _chooseInvoice(returnData.invoiceType,(value)=>{
                    let params = {
                        source: "ENTRY",
                        type: "SELECT_INVOICE",
                        invoiceType: returnData.invoiceType, // 类型：1 微信  2 支付宝
                        rid: returnData.rid, // 发票云传过来的 id
                        list: value,
                       
                    }
                    console.log('_chooseInvoice--------equipment',equipment);
                    if(equipment.isWx === false){
                        getCpUser((value)=>{
                            params = Object.assign(params,{
                                appKey: value
                            });
                            this.sendResult('SELECT_INVOICE',params);
                        })
                        
                    }else{
                        this.sendResult('SELECT_INVOICE',params);
                    }
                });
                break;    
            case 'ON_CHOOSE_IMAGE':
                this.takePicture(this,{rid:returnData.rid});
                break; 
            case 'REDIRECT': //需要跳转到我的票夹
                this.props.history.push('/wallet');
                break;                            
            default :
                break;                    
        }

        
    }  

    //发送数据到 iframe
    sendResult = (type,data)=>{
        const {baseStore} = this.props;
        const {getInvoiceCloudToken,invoiceCloudInfo} = baseStore;

        let that = this;
        switch(type){
            case 'UPDATE_TOKEN' :
                getInvoiceCloudToken({tokenUnusual:1},()=>{
                    that.sendMessage({
                        type: 'UPDATE_TOKEN',
                        token: baseStore.invoiceCloudInfo.token
                    });
                })
                break;
            case 'SCAN_QRCODE' :  
                that.sendMessage(data)
                break;
            case 'SELECT_INVOICE' :  
                that.sendMessage(data)
                break;
            case 'CHOOSE_IMAGE':
                that.sendMessage(data)
                break;
        }

    }

    //统一发送数据
    sendMessage = (data) =>{
        const {invoiceCloudInfo} = this.props.baseStore;
        let childFrame = document.getElementById("myIframe");
        let url = invoiceCloudInfo.jsUrl;
        console.log('sendMessage----------data',data);
        childFrame.contentWindow.postMessage(data, url); 
    }

    //获取所有 发票拍照数据
    getlocalIdData = (params,data,send) =>{
        if(send){ 
            let localParams = {
                source: "ENTRY",
                type: "CHOOSE_IMAGE",
                rid: params.rid, // 发票云传过来的 id,
                list:data
                
            }
            
            this.sendMessage(localParams);
            
        }
    }

    //拍照
    takePicture = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};
        
        let that = this;
        let localIdArr = [];
        let num = 0;
        window.em_ssoInit().then(() => {
            
            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let localIds = res.localIds; // 返回选定照片的本地ID列表

                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
                                num++;
                                let data = res.localData;
                                let base64PicData = "data:image/jpeg;base64,"+data;
                                let bool = localIds.length == num ? true : false;

                                let listEle = {
                                    base64:base64PicData,
                                    fileName: '',
                                }
                                localIdArr.push(listEle);

                                that.getlocalIdData(params,localIdArr,bool)
                            }
                        });
                    });

                }
            });
        }).catch((res) => {
            alert("连续拍照插件异常,使用原始插件");
            // alert(JSON.stringify(res));
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    } 
    

}

export default Reception;